package cn.com.thingo.shyintelligent.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.RadioGroup;

import com.th.opensdk.openapi.AlarmMessageInfo;
import com.th.opensdk.openapi.NotificationInfo;
import com.th.opensdk.openapi.THOpenSDK;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.thingo.shyintelligent.R;
import cn.com.thingo.shyintelligent.base.BaseActivity;
import cn.com.thingo.shyintelligent.base.contract.MainContract;
import cn.com.thingo.shyintelligent.download.DownloadApk;
import cn.com.thingo.shyintelligent.model.bean.CommonBean;
import cn.com.thingo.shyintelligent.presenter.MainPresenter;
import cn.com.thingo.shyintelligent.ui.fragment.ControlFragment;
import cn.com.thingo.shyintelligent.ui.fragment.MonitorFragment;
import cn.com.thingo.shyintelligent.ui.fragment.ScenesFragment;
import cn.com.thingo.shyintelligent.ui.receiver.THOpenReceiver;
import cn.com.thingo.shyintelligent.util.Eyes;
import cn.com.thingo.shyintelligent.util.FragmentTabUtils;
import cn.com.thingo.shyintelligent.util.SPUtils;
import cn.com.thingo.shyintelligent.util.ToastUtil;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {
    @BindView(R.id.main_radio_group)
    RadioGroup rgMain;

    public static final String EZ_ACCESS_TOKEN_SUCCEED_ACTION = "SUCCEED";
    private List<Fragment> fragments = new ArrayList<>();
    //定义一个变量，来标识是否退出
    private static boolean isExit = false;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    private THOpenReceiver receiver;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.shortShow("再按一次退出程序");
            //利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
        Eyes.setStatusBarColor(this, ContextCompat.getColor(this, R.color.btn_color));
        //1.注册下载广播接收器
        DownloadApk.registerBroadcast(this);
        //2.删除已存在的Apk
        DownloadApk.removeFile(this);
        initView();
        initReceiver();
    }

    private void initReceiver() {
        receiver = new THOpenReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(NotificationInfo.BROADCAST_ALARM_MESSAGE_UPLOAD);
        filter.addAction(NotificationInfo.BROADCAST_DATA_UPDATED_FINISH);
        filter.addAction(NotificationInfo.BROADCAST_DATA_UPDATED_START);
        filter.addAction(NotificationInfo.BROADCAST_DEVICE_STATE_UPLOAD);
        filter.addAction(NotificationInfo.BROADCAST_GATEWAY_STATUS_CHANGED);
        registerReceiver(receiver, filter);

    }

    private void initView() {
        fragments.add(ControlFragment.newInstance());
        fragments.add(ScenesFragment.newInstance());
        fragments.add(MonitorFragment.newInstance());
        FragmentTabUtils fragmentTabUtils = new FragmentTabUtils(getSupportFragmentManager(), fragments, R.id.main_fragment, rgMain);
        fragmentTabUtils.onCheckedChanged(rgMain, rgMain.getChildAt(0).getId());
    }

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            ActivityCompat.finishAfterTransition(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        SPUtils.newInstance().remove(SPUtils.CURRENT_ROOM_ID);
    }

    //    @Override
//    public void doUpdate(UpdateBean updateBean) {
//        final String url = updateBean.getData().getUrl();         //更新url
//        final String content = updateBean.getData().getContent();         //更新的内容
//
//        new MaterialDialog.Builder(MainActivity.this)
//                .title("更新")
//                .content(content)
//                .positiveText("立即更新")
//                .negativeText("以后再说")
//                .positiveColor(mContext.getResources().getColor(R.color.gray_6))
//                .negativeColor(mContext.getResources().getColor(R.color.gray_6))
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        //3.如果手机已经启动下载程序，执行downloadApk。否则跳转到设置界面
//                        if (DownLoadUtils.getInstance(getApplicationContext()).canDownload()) {
//                            DownloadApk.downloadApk(getApplicationContext(), url, "更新", "找找");
//                        } else {
//                            DownLoadUtils.getInstance(getApplicationContext()).skipToDownloadManager();
//                        }
//                    }
//                })
//                .onNegative(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        dialog.dismiss();
//                    }
//                })
//                .show();
//    }


    @Override
    protected void onDestroy() {
        //4.反注册广播接收器
        //有时报反注册失败crash  Receiver not registered 应该需要用try catch
        DownloadApk.unregisterBroadcast(this);
        super.onDestroy();
        unregisterReceiver(receiver);
        THOpenSDK.getInstance().logoutGateway();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    public void callBackMessage(AlarmMessageInfo alarmMessageInfo) {
        mPresenter.addMessage(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN), "报警消息", "网关:".concat(SPUtils.newInstance().getString(SPUtils.GATEWAY_CURRENT_NAME)).concat("触发").concat(alarmMessageInfo.getMessage()));

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 500 && resultCode == 500) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }


    @Override
    public void viewAddMessage(CommonBean commonBean) {
        ((ControlFragment) (fragments.get(0))).messageCount();
        ((ScenesFragment) (fragments.get(1))).messageCount();
        ((MonitorFragment) (fragments.get(2))).messageCount();

    }


}
